#!/bin/bash

# OTA-Package
if [ "$#" -ne 2 ]; then
    echo "Usage: $0 {major|minor|patch} <increment>"
    exit 1
fi

PACKAGE_NAME=rads 
PACKAGE_PATH=$(echo $ROS_PACKAGE_PATH | cut -d: -f1)
PACKAGE_OTA_PATH="${PACKAGE_PATH}/${PACKAGE_NAME}"

PART=$1
INCREMENT=$2
PACKAGE_XML_FILE="${PACKAGE_OTA_PATH}/package.xml"
PACKAGE_XML_FILE_NEW="${PACKAGE_OTA_PATH}/package2.xml"
PACKAGE_XML_FILE_TEMP="${PACKAGE_OTA_PATH}/package_temp.xml"

if ! [[ "$INCREMENT" =~ ^[0-9]+$ ]]; then
    echo "Error: Increment must be a valid non-negative integer."
    exit 1
fi

if ! [[ "$PART" =~ ^(major|minor|patch)$ ]]; then
    echo "Error: Invalid part specified. Use 'major', 'minor', or 'patch'."
    exit 1
fi

CURRENT_VERSION=$(xmlstarlet sel -t -v "//version" "$PACKAGE_XML_FILE" 2>/dev/null)
if [ $? -ne 0 ]; then
    echo "Error: Failed to retrieve current version using xmlstarlet."
    exit 1
fi
if ! [[ "$CURRENT_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo "Error: Current version format is invalid."
    exit 1
fi

IFS='.' read -r -a VERSION_ARRAY <<< "$CURRENT_VERSION"

# echo "Before case: ${VERSION_ARRAY[@]}"
case "$PART" in
    major)
        VERSION_ARRAY[0]=$((VERSION_ARRAY[0] + INCREMENT))
		VERSION_ARRAY[1]=0
        VERSION_ARRAY[2]=0
        ;;
    minor)
        VERSION_ARRAY[1]=$((VERSION_ARRAY[1] + INCREMENT))
        ;;
    patch)
        VERSION_ARRAY[2]=$((VERSION_ARRAY[2] + INCREMENT))
        ;;
esac
# echo "After case: ${VERSION_ARRAY[@]}"

NEW_VERSION="${VERSION_ARRAY[0]}.${VERSION_ARRAY[1]}.${VERSION_ARRAY[2]}"

xmlstarlet ed -u "//version" -v "$NEW_VERSION" "$PACKAGE_XML_FILE" > "$PACKAGE_XML_FILE_NEW"
if [ $? -ne 0 ]; then
    echo "Error: Failed to update version using xmlstarlet."
    exit 1
fi
echo "version updated to: $NEW_VERSION"
mv $PACKAGE_XML_FILE $PACKAGE_XML_FILE_TEMP
mv $PACKAGE_XML_FILE_NEW $PACKAGE_XML_FILE
rm $PACKAGE_XML_FILE_TEMP
echo "version updated successful"

